package steg.words;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

public class StegaWord
{

	private String path;
	private String inTxt;
	private String outTxt;
	private int jump;
	private ArrayList<String> dict = new ArrayList<String>();
	private StringBuilder inTxtSB = new StringBuilder("");
	private StringBuilder outTxtSB = new StringBuilder("");

	public StegaWord(String path, String inTxt, String outTxt, int jump)
	{
		this.path=path;
		this.inTxt=inTxt;
		this.outTxt=outTxt;
		this.jump=jump;
	}

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException
	{
		String path="C:/tmp/words/";
		String inTxt="test.txt";
		String outTxt="StegaWord"+inTxt;
		int jump=8;
		
		StegaWord stegaWord= new StegaWord(path,inTxt,outTxt, jump);
		stegaWord.process();

	}

	private void process() throws IOException
	{
		loadDictionary();
		loadIntext();
		compose();
		
	}

	
	private void compose()
	{
		int outCharIndex=jump;
		for(int i=0;i<inTxtSB.length();i++)
		{
			char ch=inTxtSB.charAt(i);
			int posNewChar = jump*(i+1)-outTxtSB.length();
			int maxLengt = jump*(i+2)-outTxtSB.length()-1;
			String word = searchWord(posNewChar,ch,maxLengt);
			outTxtSB.append(word);
			outTxtSB.append(" ");
			outCharIndex=outCharIndex+jump;
			System.out.println(ch+"\t"+word);
		}
		System.out.println(outTxtSB);
		
	}

	private String searchWord(int posNewChar, char ch, int maxLengt)
	{
		ArrayList<String> res = new ArrayList<String>();
		for(String w : dict){
			if(w.length()<posNewChar)
				continue;
			if(w.length()>maxLengt)
				continue;
			//System.out.println(w.charAt(posNewChar-1));
			if(w.charAt(posNewChar-1) ==  ch)
				res.add(w);
		}
		 Collections.shuffle(res);
		return res.get(0);
	}

	private void loadIntext() throws IOException
	{
		FileInputStream fstream = new FileInputStream(path+"/"+inTxt);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		while ((strLine = br.readLine()) != null)
		{
			inTxtSB.append(strLine);
		}
		in.close();	
		
	}

	private void loadDictionary() throws IOException
	{
		FileInputStream fstream = new FileInputStream(path+"/words_italian.win.txt");
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		while ((strLine = br.readLine()) != null)
		{
			dict.add(strLine);
		}
		in.close();		
	}

}
